<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_scrm/model')->方法名();
*/
namespace jy_scrm;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function check_custom(){
		if($_SESSION['container']!='wxwork'){
			exi('请在企业微信端环境下打开！','error');
		}
		return true;
	}
	public function check_worker($openid='',$exi=false){
		if($_SESSION['container']!='wxwork'){
			$worker=pdo_get('jy_scrm_worker',array('merchid'=>$_SESSION['onemerchid'],'mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),array('id','userid'));
			$workerid=$worker['id'];
			if($worker['userid']){
				$_SESSION['workeruserid']=$worker['userid'];
			}
		}else{
			$workerid=pdo_getcolumn('jy_scrm_worker',array('merchid'=>$_SESSION['onemerchid'],'userid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid']),'id');
			if(!$_SESSION['openid']){
				exi('获取企业微信OPENID失败！请联系管理员检查应用配置（1、网页授权域名是否正确；2、应用ID、应用secret是否正确）修改参数后，刷新页面缓存才能生效！','error');
			}
			if($_SESSION['uid']){
				pdo_update('jy_scrm_worker',array('mid'=>$_SESSION['uid']),array('merchid'=>$_SESSION['onemerchid'],'userid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid']));
			}
		}
		if(!$workerid && $_SESSION['container']=='wxwork'){
			$isfans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'type'=>9,'uniacid'=>$_SESSION['uniacid'],'merchid'=>$_SESSION['onemerchid'],'isopen'=>1));
			if($isfans['nickname']){
				$params=array(
					'userid'=>$isfans['nickname'],
					'open_userid'=>$isfans['openid'],
					'name'=>$isfans['nickname'],
				);
				$workerid=$this->model('worker')->create($params);
			}
		}
		if($workerid){
			$_SESSION['workerid']=$workerid;
			if($_SESSION['container']=='wxwork'){
				$_SESSION['workeruserid']=$_SESSION['openid'];
			}
			return true;
		}else{
			if($exi){
				exi('您不是员工（或还没同步企业成员），无权访问！','error');
			}
			return false;
		}
	}
	public function add_apilog($action){
		$isadd=pdo_getcolumn('jy_scrm_apilog',array('merchid'=>$_SESSION['onemerchid'],'action'=>$action,'uniacid'=>$_SESSION['uniacid']),'id');
		if($isadd){
			$this->pdo_update('apilog',array('times +='=>1,'uptime'=>TIMESTAMP),array('merchid'=>$_SESSION['onemerchid'],'action'=>$action,'uniacid'=>$_SESSION['uniacid']));
		}else{
			$data=array(
				'uniacid'=>$_SESSION['uniacid'],
				'merchid'=>$_SESSION['onemerchid'],
				'action'=>$action,
				'times'=>1,
				'uptime'=>TIMESTAMP,
				'createtime'=>TIMESTAMP
			);
			$this->pdo_insert('apilog',$data);
		}
		return true;
	}
	public function check_apilog($action,$exi=false){
		$data=array(
			'uniacid'=>$_SESSION['uniacid'],
			'merchid'=>$_SESSION['onemerchid'],
			'action'=>$action,
		);
		$createtime=pdo_getcolumn('jy_scrm_apilog',$data,'uptime');
		if($createtime+120>TIMESTAMP){
			if($exi){
				exi('2分钟内已经获取过一次，不可重复获取！','error');	
			}
			return false;
		}
		return true;
	}
	public function get_csvitems($rows){
			$num = count($rows);
			$i = 0;
			$colsIndex = $rows[1];
			$rows = array_slice($rows, 1, count($rows) - 1);
			$items = array();
			$num = 0;
			foreach ($rows as $rownu => $rv) {
				$item = array();
				foreach ($colsIndex as $cols => $cv) {
						$item[$cv]=$rv[$cols];
				}
				$items[] = $item;
				++$num;
			}
			return $items;
	}
	public function jie_state($state,$ExternalUserID='',$UserID=''){
			if($ExternalUserID){
				$this->model('member')->up_member_item($ExternalUserID);
			}
			$state=str_array($state,'|');
			if($state[1]=='jy_worker_ewm'){
				$msg=model('jy_worker_ewm/model')->jie_state($state,$ExternalUserID,$UserID);
				return $msg;
			}
			if($state[1]=='mid'){
				$fromuser=$state[2];
			}
			if($state[3]=='game'){
				$gameid=$state[4];
				$game=pdo_get('jy_scrm_sale_game',array('id'=>$gameid,'uniacid'=>$_SESSION['uniacid']));
				$sharelink=custom_url('jy_scrm/sale.liebian//fromuser='.$fromuser,true);
				$welcome=$game['welcome']?:'无欢迎语！';
				$msg=array(
					'text'=>array(
						'content'=>$welcome,
					),
				);
				return $msg;
			}elseif($state[3]=='code'){
				$codeid=$state[4];
				$code=pdo_get('jy_scrm_code',array('id'=>$codeid,'uniacid'=>$_SESSION['uniacid']));
				$welcome=pdo_get('jy_scrm_welcome',array('id'=>$code['welcomeid']));
			}else{
				$params=array('uniacid'=>$_SESSION['uniacid']);				
				//员工
				if($UserID){
					$bumenids=$this->pdo_getcolumn('worker',array('merchid'=>$_SESSION['onemerchid'],'userid'=>$UserID,'uniacid'=>$_SESSION['uniacid']),'bumenids');
					$bumenids=str_array($bumenids);
					if($bumenids){
						$params['bumenid']=$bumenids;
					}else{
						$params['is_default']=1;
					}
				}else{
					$params['is_default']=1;
				}
				$username=$this->pdo_getcolumn('member',array('merchid'=>$_SESSION['onemerchid'],'external_userid'=>$ExternalUserID,'uniacid'=>$_SESSION['uniacid']),'name');
				$username=$username?:'无昵称';
				$welcome=pdo_get('jy_scrm_welcome',$params);
			}
			if(!$welcome){
					$params['is_default']=0;
					unset($params['bumenid']);
					$welcome=pdo_get('jy_scrm_welcome',array('merchid'=>$_SESSION['onemerchid'],'uniacid'=>$_SESSION['uniacid']));
			}
				$welcome['image']=$welcome['image']?json_decode($welcome['image'],true):array();
				$welcome['link']=$welcome['link']?json_decode($welcome['link'],true):array();
				$welcome['miniprogram']=$welcome['miniprogram']?json_decode($welcome['miniprogram'],true):array();
				$welcome['video']=$welcome['video']?json_decode($welcome['video'],true):array();
				$welcome['file']=$welcome['file']?json_decode($welcome['file'],true):array();
				//if($welcome['content']==urlencode(urldecode($welcome['content']))){
					$welcome['content']=urldecode($welcome['content']);
				//}
				$welcome['content']=str_replace('[客户名称]',$username,$welcome['content']);
				$attachments=array();
				if($welcome['miniprogram']['title']){
					$attachments[]=array(
						'msgtype'=>'miniprogram',
						'miniprogram'=>array(
							'title'=>$welcome['miniprogram']['title'],
							'pic_media_id'=>$welcome['miniprogram']['pic_media_id'],
							'appid'=>$welcome['miniprogram']['appid'],
							'page'=>$welcome['miniprogram']['path'],
						),
					);
				}
				if($welcome['image']['media_id']){
					$attachments[]=array(
						'msgtype'=>'image',
						'image'=>array(
							'media_id'=>$welcome['image']['media_id'],
						),
					);
				}
				if($welcome['video']['media_id']){
					$attachments[]=array(
						'msgtype'=>'video',
						'video'=>array(
							'media_id'=>$welcome['video']['media_id'],
						),
					);
				}
				if($welcome['link']['title']){
					$attachments[]=array(
						'msgtype'=>'link',
						'link'=>array(
							'title'=>$welcome['link']['title'],
							'picurl'=>tomedia($welcome['link']['picurl']),
							'desc'=>$welcome['link']['desc'],
							'url'=>$welcome['link']['url'],
						),
					);
				}
				$msg=array(
						'text'=>array(
							'content'=>$welcome['content'],
						),
						'attachments'=>$attachments,
				);
				return $msg;
	}
	public function giftmsg($state,$ExternalUserID='',$UserID=''){
			$_SESSION['onemerchid']=$_SESSION['onemerchid']?:0;
			$state=str_array($state,'|');
			if($state[1]=='mid'){
				$fromuser=$state[2];
			}
			$params=array('uniacid'=>$_SESSION['uniacid']);
			//员工
			if($UserID){
				$workerid=pdo_getcolumn('jy_scrm_worker',array('merchid'=>$_SESSION['onemerchid'],'userid'=>$UserID,'uniacid'=>$_SESSION['uniacid']),'id');
			}
			if(!$workerid){
				return false;
			}
			$member=pdo_get('jy_scrm_member',array('merchid'=>$_SESSION['onemerchid'],'external_userid'=>$ExternalUserID,'uniacid'=>$_SESSION['uniacid']),array('mid','name'));
			$giftlog=pdo_get('jy_scrm_worker_giftlog',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$member['mid'],'merchid'=>$_SESSION['onemerchid'],'workerid'=>$workerid),'id');
			if($giftlog['id']){
				return false;
			}
			$username=$member['name']?:'无昵称';
			$gift=pdo_get('jy_scrm_worker_gift',array('merchid'=>$_SESSION['onemerchid'],'workerid'=>$workerid,'uniacid'=>$_SESSION['uniacid']));
			if(!$gift['status'] || $gift['endtime']<time()){
				return false;
			}
			$gift['reward'] =json_decode($gift['reward'],true);
			foreach($gift['reward'] as $rv){
				if(!$rv['type']){
					if($rv['credit_type'] && $rv['credit_num']>0){
						if($_SESSION['onemerchid']){
							model('jy_merch/member')->member_credit($_SESSION['onemerchid'],$member['mid'],'credit'.$rv['credit_type'],$rv['credit_num'],true,'jy_scrm','加好友送币');
						}else{
							model('core/member')->member_credit($member['mid'],'credit'.$rv['credit_type'],$rv['credit_num'],true,'jy_scrm','加好友送币');
						}
					}
				}elseif($rv['type']==1){
					if($rv['couponid'] && $rv['coupon_num']>0){
						for($i=0;$i<$rv['coupon_num'];$i++){
							model('jy_weishop/coupon')->getcoupon($rv['couponid'],$member['mid'],'',true,$_SESSION['onemerchid']);
						}
					}
				}elseif($rv['type']==2){
					if($rv['jy_bigwheelid'] && $rv['game_num']>0){
						for($i=0;$i<$rv['game_num'];$i++){
							$indata=array(
								'mid'=>$member['mid'],
								'game_id'=>$rv['jy_bigwheelid'],
								'plugin_name'=>'jy_bigwheel',
								'remark'=>'加好友抽奖机会',
							);
							model('jy_weishop/game')->add_game($indata);
						}
					}
				}
			}
			$giftlog=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$member['mid'],
				'merchid'=>$_SESSION['onemerchid'],
				'workerid'=>$workerid,
				'reward'=>ijson_encode($gift['reward']),
				'status'=>1,
				'createtime'=>TIMESTAMP,
			);
			$this->pdo_insert('worker_giftlog',$giftlog);
			$gift['msg']=urldecode($gift['msg']);
			$gift['msg']=str_replace('[客户名称]',$username,$gift['msg']);
			$msg=array(
				'text'=>array(
					'content'=>$gift['msg'],
				),
			);
			if(!$gift['msg']){
				return false;
			}
			return $msg;
	}
	public function upqun_welcome($id,$data=array()){
		$item=pdo_get('jy_scrm_qun_welcome',array('id'=>$id,'uniacid'=>$_SESSION['uniacid']));
		$data['text']=array(
			'content'=>urldecode($data['content']),
		);
		$template_id=model('core/wxwork_userapi')->upqun_welcome($item['template_id'],$data);
		return $template_id;
	}
	//https://developer.work.weixin.qq.com/document/path/92130
	public function add_external_contact($postdata,$noexi=false){
		$external_userid=$postdata['ExternalUserID'];
		if($external_userid){
			$this->model('member')->up_member_item($external_userid);
		}
		return true;
	}
	public function edit_external_contact($postdata,$noexi=false){
		$external_userid=$postdata['ExternalUserID'];
		if($external_userid){
			$this->model('member')->up_member_item($external_userid);
		}
		return true;
	}
	public function add_half_external_contact($postdata,$noexi=false){
		$external_userid=$postdata['ExternalUserID'];
		if($external_userid){
			$this->model('member')->up_member_item($external_userid);
		}
		return true;
	}
	public function del_external_contact($postdata,$noexi=false){
		$external_userid=$postdata['ExternalUserID'];
		if(!$external_userid){
			return false;
		}
		$update=array(
			'isdel'=>1,
			'del_worker'=>$postdata['UserID'],
			'del_time'=>$postdata['CreateTime']?:TIMESTAMP,
		);
		$this->pdo_update('member',$update,array('external_userid'=>$external_userid,'uniacid'=>$_SESSION['uniacid']));
		return true;
	}
	public function del_follow_user($postdata,$noexi=false){
		$external_userid=$postdata['ExternalUserID'];
		if(!$external_userid){
			return false;
		}
		$update=array(
			'isdel'=>1,
			'del_worker'=>'',
			'del_time'=>$postdata['CreateTime']?:TIMESTAMP,
		);
		$this->pdo_update('member',$update,array('external_userid'=>$external_userid,'uniacid'=>$_SESSION['uniacid']));
		return true;
	}
	public function chat_add($postdata,$noexi=false){
		$ChatId=$postdata['ChatId'];
		if(!$ChatId){
			return false;
		}
		$this->model('member')->up_qun_item($ChatId);
		return true;
	}
	public function chat_dismiss($postdata,$noexi=false){
		$ChatId=$postdata['ChatId'];
		if(!$ChatId){
			return false;
		}
		$update=array(
			'isdel'=>1,
			'del_time'=>$postdata['TimeStamp']?:TIMESTAMP,
		);
		$this->pdo_update('qun',$update,array('chat_id'=>$ChatId,'uniacid'=>$_SESSION['uniacid']));
		return true;
	}
	public function tag_add($postdata,$noexi=false){
		$Id=$postdata['Id'];
		if(!$Id){
			return false;
		}
		$this->model('member')->up_tags();
		return true;
	}
	public function tag_update($postdata,$noexi=false){
		$Id=$postdata['Id'];
		if(!$Id){
			return false;
		}
		$this->model('member')->up_tags();
		return true;
	}
	public function tag_delete($postdata,$noexi=false){
		$Id=$postdata['Id'];
		if(!$Id){
			return false;
		}
		$update=array(
			'status'=>1,
			'isdel'=>1,
			'del_time'=>$postdata['TimeStamp']?:TIMESTAMP,
		);
		$this->pdo_update('jy_scrm_member_group_tag',$update,array('tag_id'=>$Id,'uniacid'=>$_SESSION['uniacid']));
		return true;
	}
}
?>